package com.socket.socket;

import java.io.*;
import java.net.Socket;

public class TestClient {
    public static void main(String[] args) {
        String serverHost = "127.0.0.1"; // 服务端地址
        int serverPort = 7888;          // 服务端端口号

        try (Socket socket = new Socket(serverHost, serverPort);
             BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))) {

            System.out.println("客户端已连接到服务端: " + serverHost + ":" + serverPort);

            // 开启一个线程持续接收服务端消息
            new Thread(() -> {
                try {
                    String serverMessage;
                    while ((serverMessage = reader.readLine()) != null) {
                        System.out.println("服务端消息: " + serverMessage);
                    }
                } catch (IOException e) {
                    System.err.println("接收消息时发生错误: " + e.getMessage());
                }
            }).start();

            // 模拟发送多条消息
            for (int i = 0; i < 5; i++) {
                String message = "{\"services\": [{\"service_id\": \"spaceport\", \"properties\": {\"light\": \"100Lux\", \"th\": \"25℃\", \"wet\": \"50%\", \"led\": \"ON\"}}]}";
                writer.write(message);
                writer.newLine();
                writer.flush();
                System.out.println("发送消息: " + message);

                // 等待3秒模拟消息间隔
                Thread.sleep(3000);
            }

            // 模拟发送完消息后保持连接
            System.out.println("所有消息已发送，客户端保持连接中...");
            Thread.sleep(60000); // 等待一分钟观察服务端是否断开连接

        } catch (IOException | InterruptedException e) {
            System.err.println("客户端发生错误: " + e.getMessage());
        }
    }
}
